<template>
  <van-form ref="formRef">
    <div class="big-box">
      <!-- <div class="small-box">图片</div> -->
      <div class="small-box">
        <van-row type="flex" justify="center">
          <van-col span="24"
            ><van-field label="姓名" v-model="ownName" readonly
          /></van-col>
        </van-row>
        <van-row type="flex" justify="center" v-if="webType === 1">
          <van-col span="24">
            <van-field
              readonly
              clickable
              name="picker"
              :value="greenCardType"
              label="绿卡类型"
              placeholder="点击选择绿卡类型"
              @click="showGreenCardPicker = true"
              :rules="[{ required: true, message: '关键人姓名为必填项' }]"
            >
              <!-- <template #label>
                <span class="required-star">*</span>关键人姓名
              </template> -->
            </van-field>
            <van-popup v-model="showGreenCardPicker" position="bottom">
              <van-picker
                show-toolbar
                :columns="greenCardTypes"
                @confirm="onConfirm"
                @cancel="showGreenCardPicker = false"
              />
            </van-popup>
          </van-col>
        </van-row>
        <van-row type="flex" justify="center">
          <van-col span="24"
            ><van-field label="发起人部门" v-model="depName" readonly
          /></van-col>
        </van-row>
        <van-row type="flex" justify="center">
          <van-col span="24"
            ><van-field label="所属单位" v-model="depName" readonly
          /></van-col>
        </van-row>

        <van-row type="flex" justify="center">
          <van-col span="24">
            <div style="margin: 16px">
              <van-button
                round
                block
                type="info"
                native-type="submit"
                @click="addBaseInfo"
                >继续添加</van-button
              >
            </div>
          </van-col>
        </van-row>
      </div>
      <div class="small-box" v-show="baseInfo">
        <van-row type="flex" justify="center">
          <van-col span="24"
            ><van-field
              label="贵宾卡号"
              v-model="vipCardNum"
              :rules="[{ required: true, message: '关键人姓名为必填项' }]"
            >
              <template #label>
                <span class="required-star">*</span>贵宾卡号
              </template>
            </van-field></van-col
          >
        </van-row>
        <van-row type="flex" justify="center">
          <van-col span="24"
            ><van-field
              label="单位名称"
              v-model="depName"
              :rules="[{ required: true, message: '单位名称为必填项' }]"
            >
              <template #label>
                <span class="required-star">*</span>单位名称
              </template>
            </van-field></van-col
          >
        </van-row>
        <van-row type="flex" justify="center">
          <van-col span="24">
            <van-field
              label="小户名"
              v-model="keyPersonName"
              :rules="[{ required: true, message: '小户名为必填项' }]"
            >
              <template #label>
                <span class="required-star">*</span>小户名
              </template>
            </van-field>
          </van-col>
        </van-row>
        <van-row type="flex" justify="center">
          <van-col span="24"
            ><van-field
              label=""
              v-model="bussinessCountNumber"
              :rules="[{ required: true, message: '此处为必填项' }]"
            >
              <template #label>
                <span class="required-star">*</span>包保合同号
              </template></van-field
            >
          </van-col>
        </van-row>
        <van-row type="flex" justify="center" >
          <van-col span="24">
            <van-field
              label=""
              :rules="[{ required: true, message: '数量为必填项' }]"
            >
              <template #input>
                <van-button size="small" @click="decreaseCount">-</van-button>
                <input
                  type="number"
                  v-model="count"
                  style="width: 50px; text-align: center; margin: 0 5px"
                />
                <van-button size="small" @click="increaseCount">+</van-button>
              </template>
              <template #label>
                <span class="required-star">*</span>数量
              </template>
            </van-field>
          </van-col>
        </van-row>
        <van-row type="flex" justify="center">
          <van-col span="24">
            <van-field
              readonly
              clickable
              name="picker"
              :value="discountMonth"
              label="优惠总月份"
              placeholder="点击选择优惠总月份"
              @click="dicountMonthPicker = true"
              :rules="[{ required: true, message: '优惠总月份为必填项' }]"
            >
              <template #label>
                <span class="required-star">*</span>优惠总月份
              </template>
            </van-field>
            <van-popup v-model="dicountMonthPicker" position="bottom">
              <van-picker
                show-toolbar
                :columns="discountMonths"
                @confirm="onConfirmDiscountMonth"
                @cancel="dicountMonthPicker = false"
              />
            </van-popup>
          </van-col>
        </van-row>
        <van-row type="flex" justify="center">
          <van-col span="24">
            <van-field
              readonly
              :value="amount"
              label="总金额"
              placeholder="点击输入金额"
              @click="showKeyboard = true"
              :rules="[{ required: true, message: '总金额为必填项' }]"
            >
              <template #label>
                <span class="required-star">*</span>总金额
              </template>
            </van-field>
            <van-number-keyboard
              v-model="amount"
              :show="showKeyboard"
              theme="custom"
              extra-key="."
              close-button-text="完成"
              @delete="onKeyboardDelete(1)"
              @blur="closeKeyboard(1)"
            />
          </van-col>
        </van-row>
        <van-row type="flex" justify="center" >
          <van-col span="24">
            <van-field
              readonly
              :value="amountPerMonth"
              label="总金额"
              placeholder="点击输入金额"
              @click="showKeyboardPerMonth = true"
              :rules="[{ required: true, message: '每月大单减免金额为必填项' }]"
            >
              <template #label>
                <span class="required-star">*</span>每月大单减免金额
              </template>
            </van-field>
            <van-number-keyboard
              v-model="amountPerMonth"
              :show="showKeyboardPerMonth"
              theme="custom"
              extra-key="."
              close-button-text="完成"
              @delete="onKeyboardDelete(2)"
              @blur="closeKeyboard(2)"
            />
          </van-col>
        </van-row>
        <van-row type="flex" justify="center">
          <van-col span="24">
            <van-field
              readonly
              clickable
              :value="selectedDateTime"
              label="选择日期时间"
              placeholder="点击选择日期时间"
              @click="showDateTimePicker = true"
              :rules="[{ required: true, message: '日期时间为必填项' }]"
            >
              <template #label>
                <span class="required-star">*</span>服务开始时间
              </template>
            </van-field>
            <van-popup v-model="showDateTimePicker" position="bottom">
              <van-datetime-picker
                type="datetime"
                @confirm="onDateTimeConfirm"
                @cancel="showDateTimePicker = false"
              />
            </van-popup>
          </van-col>
        </van-row>
        <van-row type="flex" justify="center">
          <van-col span="24">
            <van-field
              readonly
              :value="endTime"
              label="结束时间"
              placeholder="点击选择结束时间"
              :disabled="isDateTimePickerDisabled"
              :rules="[{ required: true, message: '结束时间为必填项' }]"
            >
              <template #label>
                <span class="required-star">*</span>结束时间
              </template>
            </van-field>
          </van-col>
        </van-row>
        <van-row type="flex" justify="center">
          <van-col span="24">
            <van-field
              v-model="reason"
              label="理由"
              placeholder="请输入理由"
              type="textarea"
              autosize
              :rules="[{ required: true, message: '理由为必填项' }]"
            >
              <template #label>
                <span class="required-star">*</span>理由
              </template>
            </van-field>
          </van-col>
        </van-row>
        <van-row type="flex">
          <van-col span="5" style=""
            ><div class="upload-label">上传文件</div></van-col
          >
          <van-col span="12">
            <van-uploader :after-read="afterRead" :max-count="3" multiple>
            </van-uploader>
          </van-col>
        </van-row>
        <van-row type="flex" justify="center">
          <van-col span="24">
            <div style="margin: 16px">
              <van-button
                round
                block
                type="info"
                native-type="submit"
                @click="submit"
                >提交</van-button
              >
            </div>
          </van-col>
        </van-row>
      </div>
    </div>
  </van-form>
</template>

<script>
import Demcimal from "decimal.js";
export default {
  components: {},
  props: {},
  data() {
    return {
      greenCardTypes: ["包保", "光纤", "酒盟", "项目赠送"],
      showGreenCardPicker: false,
      webType: 1,
      ownName: "测试",
      vipCardNum: "0576-----",
      depName: "玉环政务行客支局",
      keyPersonName: "0576000000",
      greenCardType: "包保",
      keyPersonDepName: "123123",
      keyPersonJob: "秘书",
      value: "",
      enjoyPersonName: "",
      bussinessCountNumber: "",
      bussinessCountNumbers: [5],
      keyPersonDepNames: ["玉环政务行客支局", "玉环政务行客支局"],
      showKeyPersonDepNamePicker: false,
      keyPeronNames: ["张三", "李四"],
      enjoyPeronNames: ["王五", "小刘"],
      realationshipWithKerperson: "本人",
      bussinessType: "",
      baseInfo: true,
      columns: ["大单优惠", "服务卡"],
      showKeyPersonNamePicker: false,
      showEnjoyPeronNamePicker: false,
      showBussinessCountNumberPicker: false,
      cardType: "",
      cardTypes: ["金卡", "银卡", "普通卡"],
      discountMonth: "1",
      dicountMonthPicker: false,
      discountMonths: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12],
      showCardTypePicker: false,
      count: 1,
      selectedDateTime: "",
      showDateTimePicker: false,
      endTime: "",
      isDateTimePickerDisabled: false,
      reason: "",
      uploadedFiles: [],
      amount: "",
      amountPerMonth: "",
      showKeyboardPerMonth: false,
      showKeyboard: false,
      checkTag: false,
    };
  },
  computed: {},
  watch: {
    greenCardType(newVal) {
      if (newVal === "包保") {
        this.webType = 1;
      }
      if (newVal === "光纤") {
        this.webType = 2;
      }
      if (newVal === "酒盟") {
        this.webType = 3;
      }
      if (newVal === "项目赠送") {
        this.webType = 4;
      }
    },
    selectedDateTime(newVal) {
      // 假设使用 discountMonth 作为要增加的月份数，该变量在你的代码中已定义
      this.calDate(newVal);
    },
    amount(newVal) {
      this.amount = this.handleAmountInput(newVal);
    },
    amountPerMonth(newVal) {
      this.amountPerMonth = this.handleAmountInput(newVal);
    },
    discountMonth(newVal) {
      if (this.amount) {
        this.amountPerMonth = new Demcimal(this.amountPerMonth)
          .div(newVal)
          .toFixed(2);
      }
      if (this.selectedDateTime) {
        this.calDate(this.selectedDateTime, newVal);
      }
    },
  },
  created() {
    if (this.$route.query.itemTitle == "服务卡") {
      this.webType = 1;
      this.greenCardType = this.$route.query.itemTitle;
    }
    if (this.$route.query.itemTitle == "大单优惠") {
      this.webType = 2;
      this.greenCardType = this.$route.query.itemTitle;
    }
  },
  mounted() {},
  methods: {
    calDate(val, month) {
      if (!month) {
        month = this.discountMonth;
      }
      const selectedDate = new Date(val);
      const monthsToAdd = parseInt(month, 10);
      selectedDate.setMonth(selectedDate.getMonth() + monthsToAdd);
      this.endTime = selectedDate.toLocaleString();
    },
    onConfirm(value) {
      this.greenCardType = value;
      this.showGreenCardPicker = false;
    },
    onConfirm2(value) {
      this.enjoyPersonName = value;
      this.showEnjoyPeronNamePicker = false;
    },
    onConfirm3(value) {
      this.bussinessCountNumber = value;
      this.showBussinessCountNumberPicker = false;
    },
    onConfirmCardType(value) {
      this.cardType = value;
      this.showCardTypePicker = false;
    },
    onConfirmDiscountMonth(value) {
      this.discountMonth = value;
      this.dicountMonthPicker = false;
    },
    onConfirmDepName(val) {
      this.keyPersonDepName = val;
      this.showKeyPersonDepNamePicker = false;
    },
    increaseCount() {
      this.count++;
    },
    decreaseCount() {
      if (this.count > 1) {
        this.count--;
      }
    },
    onDateTimeConfirm(value) {
      // 可根据需求格式化日期时间
      this.selectedDateTime = value.toLocaleString();
      this.showDateTimePicker = false;
    },
    handleAmountInput(value) {
      // 去除非数字和小数点的字符
      let amount = value.replace(/[^\d.]/g, "");
      // 处理多个小数点的情况
      amount = amount.replace(/\.{2,}/g, ".");
      // 确保小数点只出现一次
      amount = amount.split(".").slice(0, 2).join(".");
      // 处理小数点后的位数，保留两位小数
      const parts = amount.split(".");
      if (parts.length > 1) {
        parts[1] = parts[1].slice(0, 2);
      }
      amount = parts.join(".");
      // 去除开头的 0，除非是 0 或 0.xx
      if (amount.startsWith("0") && amount.length > 1 && amount[1] !== ".") {
        amount = amount.slice(1);
      }
      return amount;
    },
    // onKeyboardInput(key) {

    // },
    onKeyboardDelete(val) {
      if (val === 1) {
        if (this.amount.length > 0) {
          this.amount = this.amount.slice(0, -1);
        }
      }
      if (val === 2) {
        this.amountPerMonth = this.amountPerMonth.slice(0, -1);
      }
    },
    closeKeyboard(val) {
      if (val === 1) {
        if (this.discountMonth.length > 0 && this.amount.length > 0) {
          this.amountPerMonth = new Demcimal(this.amount)
            .div(this.discountMonth)
            .toFixed(2);
        }
        this.showKeyboard = false;
      }
      if (val === 2) {
        if (this.amountPerMonth.length > 0 && this.discountMonth.length > 0) {
          this.amount = new Demcimal(this.amountPerMonth)
            .mul(this.discountMonth)
            .toFixed(2);
        }
        this.showKeyboardPerMonth = false;
      }
    },
    addBaseInfo() {
      this.baseInfo = true;
    },
    submit() {
      console.log("[ 111 ] >", 111);
      if (this.$refs.formRef) {
        this.$refs.formRef
          .validate()
          .then(() => {
            // 校验通过，执行提交逻辑
            console.log("表单校验通过，提交数据:", "dd");
          })
          .catch((error) => {
            // 处理校验失败的情况
            console.error("表单校验失败:", error);
          });
      }
    },
    afterRead(file) {
      // 这里可以进行文件上传操作，例如发送到服务器
      console.log("选择的文件:", file);
      this.uploadedFiles.push(file);
    },
  },
};
</script>

<style scoped>
/* .van-field {
  border-bottom: 1px solid rgb(252, 252, 247);
} */
:deep(.van-field__label) {
  width: 9rem;
}
.required-star {
  color: red;
  margin-right: 4px;
}
.upload-label {
  font-size: 14px;
  color: #333;
  line-height: 32px;
  margin-bottom: 8px;
  text-align: right; /* 让 label 文字右对齐 */
  padding-right: 10px; /* 增加右侧内边距 */
}
.big-box {
  display: flex;
  flex-direction: column;
  height: 1000px;
  width: 100%;
}

/* 小盒子通用样式 */
.small-box {
  border: 1px solid #ccc;
  text-align: center;
  /* line-height: 100px; */
  margin-top: 10px;
}

/* 为每个小盒子设置不同背景色以作区分 */
.small-box:nth-child(1) {
  flex: 1;
  background-color: rgb(249, 249, 249);
  height: 400px;
}

.small-box:nth-child(2) {
  flex: 2;
  background-color: rgb(249, 249, 249);
}

.small-box:nth-child(3) {
  flex: 3;
  background-color: rgb(249, 249, 249);
}
.van-field--disabled {
  color: #ccc; /* 置灰文字颜色 */
  cursor: not-allowed; /* 禁用鼠标指针样式 */
}
</style>